document.addEventListener('DOMContentLoaded', function() {
    // 侧边栏折叠功能
    document.getElementById('sidebarCollapse').addEventListener('click', function() {
        document.getElementById('sidebar').classList.toggle('active');
        document.getElementById('content').classList.toggle('active');
    });
    
    // 页面加载时默认显示热点分析内容
    hideAllContentSections();
    document.getElementById('hotspotAnalysisContent').classList.add('active');
    document.getElementById('hotspotAnalysisBtn').classList.add('active');

    // 内容区域切换功能
    const contentSections = document.querySelectorAll('.content-section');
    const navLinks = document.querySelectorAll('#sidebar a');

    // 手动模式按钮
    document.getElementById('manualModeBtn').addEventListener('click', function(e) {
        e.preventDefault();
        hideAllContentSections();
        document.getElementById('manualModeContent').classList.add('active');
        setActiveNavLink(this);
    });

    // 自动模式按钮
    document.getElementById('autoModeBtn').addEventListener('click', function(e) {
        e.preventDefault();
        hideAllContentSections();
        document.getElementById('autoModeContent').classList.add('active');
        setActiveNavLink(this);
    });

    // 热点分析按钮
    document.getElementById('hotspotAnalysisBtn').addEventListener('click', function(e) {
        e.preventDefault();
        hideAllContentSections();
        document.getElementById('hotspotAnalysisContent').classList.add('active');
        setActiveNavLink(this);
    });

    // 热点历史按钮
    document.getElementById('hotspotHistoryBtn').addEventListener('click', function(e) {
        e.preventDefault();
        hideAllContentSections();
        document.getElementById('hotspotHistoryContent').classList.add('active');
        setActiveNavLink(this);
    });

    // 快捷键设置按钮
    document.getElementById('shortcutSettingsBtn').addEventListener('click', function(e) {
        e.preventDefault();
        hideAllContentSections();
        document.getElementById('shortcutSettingsContent').classList.add('active');
        setActiveNavLink(this);
    });

    // 系统设置按钮
    document.getElementById('systemSettingsBtn').addEventListener('click', function(e) {
        e.preventDefault();
        hideAllContentSections();
        document.getElementById('systemSettingsContent').classList.add('active');
        setActiveNavLink(this);
    });

    // 日志记录按钮
    document.getElementById('logsBtn').addEventListener('click', function(e) {
        e.preventDefault();
        hideAllContentSections();
        document.getElementById('logsContent').classList.add('active');
        setActiveNavLink(this);
    });

    // 隐藏所有内容区域
    function hideAllContentSections() {
        contentSections.forEach(function(section) {
            section.classList.remove('active');
        });
    }

    // 设置当前活动的导航链接
    function setActiveNavLink(link) {
        navLinks.forEach(function(navLink) {
            navLink.classList.remove('active');
        });
        link.classList.add('active');
    }

    // 全选/取消全选视频
    document.getElementById('selectAllVideos').addEventListener('change', function() {
        const videoCheckboxes = document.querySelectorAll('.video-select');
        videoCheckboxes.forEach(function(checkbox) {
            checkbox.checked = this.checked;
        }, this);
    });

    // 一键发布按钮
    document.getElementById('oneClickPublishBtn').addEventListener('click', function() {
        // 获取选中的视频
        const selectedVideos = document.querySelectorAll('.video-select:checked');
        if (selectedVideos.length === 0) {
            showToast('请选择至少一个视频进行发布', 'warning');
            return;
        }

        // 获取选中的平台
        const platforms = [];
        if (document.getElementById('douyin').checked) platforms.push('抖音');
        if (document.getElementById('bilibili').checked) platforms.push('B站');
        if (document.getElementById('xiaohongshu').checked) platforms.push('小红书');

        if (platforms.length === 0) {
            showToast('请选择至少一个发布平台', 'warning');
            return;
        }

        // 模拟发布过程
        showToast(`开始发布 ${selectedVideos.length} 个视频到 ${platforms.join(', ')}`, 'info');
        
        // 更新发布状态表格
        updatePublishStatus(selectedVideos, platforms);
    });

    // 自动化控制按钮
    document.getElementById('startAutomationBtn').addEventListener('click', function() {
        showToast('自动化发布已开始', 'success');
        updateAutomationStatus('running');
    });

    document.getElementById('pauseAutomationBtn').addEventListener('click', function() {
        showToast('自动化发布已暂停', 'info');
        updateAutomationStatus('paused');
    });

    document.getElementById('resumeAutomationBtn').addEventListener('click', function() {
        showToast('自动化发布已恢复', 'success');
        updateAutomationStatus('running');
    });

    document.getElementById('stopAutomationBtn').addEventListener('click', function() {
        showToast('自动化发布已停止', 'warning');
        updateAutomationStatus('stopped');
    });

    // 更新自动化状态
    function updateAutomationStatus(status) {
        const statusElement = document.getElementById('automationStatus');
        const statusBadge = statusElement.querySelector('.badge');
        
        statusBadge.classList.remove('bg-success', 'bg-warning', 'bg-danger', 'bg-info');
        
        switch(status) {
            case 'running':
                statusBadge.classList.add('bg-success');
                statusBadge.textContent = '运行中';
                break;
            case 'paused':
                statusBadge.classList.add('bg-warning');
                statusBadge.textContent = '已暂停';
                break;
            case 'stopped':
                statusBadge.classList.add('bg-danger');
                statusBadge.textContent = '已停止';
                break;
            default:
                statusBadge.classList.add('bg-info');
                statusBadge.textContent = '未开始';
        }
    }

    // 更新发布状态
    function updatePublishStatus(selectedVideos, platforms) {
        const statusTableBody = document.querySelector('.publish-status table tbody');
        statusTableBody.innerHTML = '';
        
        selectedVideos.forEach(function(video, videoIndex) {
            const videoName = video.closest('tr').querySelector('.video-name').textContent;
            
            platforms.forEach(function(platform, platformIndex) {
                const row = document.createElement('tr');
                const progress = Math.floor(Math.random() * 100); // 模拟进度
                const status = progress < 100 ? '上传中' : '已完成';
                const statusClass = progress < 100 ? 'text-warning' : 'text-success';
                
                row.innerHTML = `
                    <td><i class="bi bi-${platform === '抖音' ? 'music-note-beamed' : platform === 'B站' ? 'play-btn' : 'book'}"></i> ${platform}</td>
                    <td>${videoName}</td>
                    <td class="${statusClass}">${status}</td>
                    <td>
                        <div class="progress">
                            <div class="progress-bar ${progress < 100 ? 'progress-bar-striped progress-bar-animated' : ''}" 
                                role="progressbar" style="width: ${progress}%" 
                                aria-valuenow="${progress}" aria-valuemin="0" aria-valuemax="100">${progress}%</div>
                        </div>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-outline-secondary me-1"><i class="bi bi-pause"></i></button>
                        <button class="btn btn-sm btn-outline-danger"><i class="bi bi-x"></i></button>
                    </td>
                `;
                
                statusTableBody.appendChild(row);
                
                // 模拟进度更新
                if (progress < 100) {
                    simulateProgressUpdate(row.querySelector('.progress-bar'), row.querySelector('td:nth-child(3)'));
                }
            });
        });
    }

    // 模拟进度更新
    function simulateProgressUpdate(progressBar, statusCell) {
        let currentProgress = parseInt(progressBar.style.width);
        const interval = setInterval(function() {
            currentProgress += Math.floor(Math.random() * 10) + 1;
            if (currentProgress >= 100) {
                currentProgress = 100;
                clearInterval(interval);
                progressBar.classList.remove('progress-bar-striped', 'progress-bar-animated');
                statusCell.textContent = '已完成';
                statusCell.className = 'text-success';
                showToast('一个视频发布完成', 'success');
            }
            
            progressBar.style.width = currentProgress + '%';
            progressBar.textContent = currentProgress + '%';
            progressBar.setAttribute('aria-valuenow', currentProgress);
        }, 1000);
    }

    // 显示通知消息
    function showToast(message, type = 'info') {
        const toastContainer = document.querySelector('.toast-container');
        if (!toastContainer) {
            const container = document.createElement('div');
            container.className = 'toast-container';
            document.body.appendChild(container);
        }
        
        const toast = document.createElement('div');
        toast.className = 'toast show';
        toast.setAttribute('role', 'alert');
        toast.setAttribute('aria-live', 'assertive');
        toast.setAttribute('aria-atomic', 'true');
        
        const iconClass = type === 'success' ? 'bi-check-circle' : 
                         type === 'warning' ? 'bi-exclamation-triangle' : 
                         type === 'error' ? 'bi-x-circle' : 'bi-info-circle';
        
        const textClass = type === 'success' ? 'text-success' : 
                         type === 'warning' ? 'text-warning' : 
                         type === 'error' ? 'text-danger' : 'text-info';
        
        toast.innerHTML = `
            <div class="toast-header">
                <i class="bi ${iconClass} ${textClass} me-2"></i>
                <strong class="me-auto">EasyShare 通知</strong>
                <small>刚刚</small>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body">
                ${message}
            </div>
        `;
        
        document.querySelector('.toast-container').appendChild(toast);
        
        // 5秒后自动关闭
        setTimeout(function() {
            toast.classList.remove('show');
            setTimeout(function() {
                toast.remove();
            }, 500);
        }, 5000);
        
        // 关闭按钮功能
        toast.querySelector('.btn-close').addEventListener('click', function() {
            toast.classList.remove('show');
            setTimeout(function() {
                toast.remove();
            }, 500);
        });
    }

    // 录制视频按钮
    document.getElementById('recordVideoBtn').addEventListener('click', function() {
        showToast('正在启动录制软件...', 'info');
        window.pywebview.api.startRecording();
    });

    document.getElementById('pauseVideoBtn').addEventListener('click', function() {
        showToast('录制已暂停', 'info');
        window.pywebview.api.pauseRecording();
    });

    document.getElementById('stopVideoBtn').addEventListener('click', function() {
        showToast('录制已停止', 'info');
        window.pywebview.api.stopRecording();
    });
});